<template>
  <a-modal
    :title='title'
    :width='width'
    :visible='visible'
    :maskClosable='false'
    :confirmLoading='confirmLoading'
    @ok='handleOk'
    @cancel='handleCancel'
    cancelText='关闭'>

    <a-spin :spinning='confirmLoading'>
      <a-form :form='form'>
        <a-row :gutter='24'>
          <a-col :span='12'>
            <a-form-item label='用途' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="[ 'purpose', validatorRules.purpose]" placeholder='请输入用途'></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='表名' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input-search v-decorator="[ 'tableName', validatorRules.tableName]" placeholder='请选择表名' read-only
                              @search='openTableNameList'>
                <a-button slot='enterButton'>选择表名</a-button>
              </a-input-search>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='表描述' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="[ 'tableDescription', validatorRules.tableDescription]" placeholder='请输入描述'
                       read-only></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='字段' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-select :disabled='!tableInfo.tableName' v-decorator="[ 'fieldName', validatorRules.fieldName]"
                        placeholder='请选择字段' @change='fieldNameChange' :allowClear='false' showSearch
                        optionFilterProp='children' :filterOption='filterOption'>
                <a-select-option v-for='(item, index) in fieldNameList' :key='index' :value='item.columnName'>
                  {{ item.columnName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='字段描述' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="[ 'fieldDescription', validatorRules.fieldDescription]"
                       placeholder='请输入字段描述'></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='字段条件' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-select v-decorator="[ 'fieldCondition', {'initialValue':'in'},validatorRules.fieldCondition]"
                        placeholder='请选择字段条件'>
                <a-select-option v-for='(item, index) in fieldConditionList' :key='index' :value='item.value'>
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='字段条件类别' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-select @change='changeFieldConditionCate'
                        v-decorator="[ 'fieldConditionCategory', validatorRules.fieldConditionCategory]"
                        placeholder='请选择字段条件类别'>
                <a-select-option v-for='(item, index) in fieldConditionCategoryList' :key='index' :value='item.value'>
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='字段条件结果' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <!--部门-->
              <template v-if="fieldConditionCategory=='depart'">
                <a-input-search :title='fieldConditionResultsText' placeholder='请选择部门'
                                v-model='fieldConditionResultsText' read-only style='width: 100%' @search='onSearch'>
                  <a-button slot='enterButton'>选择部门</a-button>
                </a-input-search>
              </template>
              <!--角色-->
              <template v-if="fieldConditionCategory=='role'">
                <a-select show-search option-filter-prop='children' :filter-option='filterOption' mode='multiple'
                          style='width: 100%' @change="(e)=>{changeRole(e,'fieldCondition')}" placeholder='请选择角色'
                          v-model='selectedRole'>
                  <a-select-option v-for='(role, roleindex) in roleList' :key='roleindex.toString()' :value='role.id'>
                    {{ role.roleName }}
                  </a-select-option>
                </a-select>
              </template>
              <!--用户-->
              <template v-if="fieldConditionCategory=='user'">
                <a-row :gutter='24'>
                  <a-col :span='3'>
                    <a-button type='primary' icon='plus' size='small' @click="openUserModal('fieldCondition')">
                      选择
                    </a-button>
                  </a-col>
                </a-row>
                <a-row :gutter='24'>
                  <a-col :span='24'>
                    <a-textarea v-model='fieldConditionResultsText' read-only placeholder='请选择用户'
                                :title='fieldConditionResultsText' :autosize='{ minRows: 1 }'></a-textarea>
                  </a-col>
                </a-row>
              </template>
              <!--常量 自定义方法-->
              <template v-if="fieldConditionCategory=='variable' || fieldConditionCategory=='function'">
                <a-textarea v-model='fieldConditionResults' placeholder='请输入字段条件结果'
                            :autosize='{ minRows: 1}'></a-textarea>
              </template>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='候选类别' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-select @change='changeCandidateCategory'
                        v-decorator="[ 'candidateCategory', validatorRules.candidateCategory]" placeholder='请选择候选类别'>
                <a-select-option v-for='(item, index) in candidateCategoryList' :key='index' :value='item.value'>
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span='12' v-if="this.form.getFieldValue('candidateCategory')==='function'">
            <a-form-item label='候选结果' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-textarea v-model='candidateResults' :autosize='{ minRows: 1}'
                          placeholder='请输入候选结果'></a-textarea>
            </a-form-item>
          </a-col>
          <!--  <a-col :span='12'>
                      <a-form-item label='节点编码' :labelCol='labelCol' :wrapperCol='wrapperCol'>
                        <a-select show-search option-filter-prop='children' :filter-option='filterOption' style='width: 100%'
                                  placeholder='请选择节点编码' v-decorator="[ 'processNodeCode', validatorRules.processNodeCode]">
                          <a-select-option v-for='(item, index) in processNodeCodeList' :key='index'
                                           :value='item.processNodeCode'>
                            {{ item.processName }} ( {{ item.processNodeName }} )
                          </a-select-option>
                        </a-select>
                      </a-form-item>
                    </a-col>-->
          <!-- 节点编码先用文本框 -->
          <a-col :span='12'>
            <a-form-item label='节点编码' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="[ 'processNodeCode', validatorRules.processNodeCode]" @change='handleNodeCode'
                       placeholder='请输入节点编码'></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='是否启用' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-switch checkedChildren='启用' unCheckedChildren='停止' @change='onChose' v-model='statusCheck'
                        :disabled="!this.form.getFieldValue('processNodeCode')" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>

    <!-- <j-select-table-name ref='tableName' @ok='tableNameCallback'></j-select-table-name> -->
    <!-- <depart-window ref='departWindow' @ok='departCallback'></depart-window> -->
    <!-- <act-select-user-modal ref='userModal' @ok='userCallback'></act-select-user-modal> -->
  </a-modal>
</template>

<script>

import { httpAction, getAction } from '@/api/manage'
import pick from 'lodash.pick'
import ACol from 'ant-design-vue/es/grid/Col'
import AInputSearch from 'ant-design-vue/es/input/Search'
import { queryall } from '@/api/api'
// import JSelectTableName from '@views/bms/actcandidateconfig/modules/JSelectTableName'
// import DepartWindow from '@views/bms/actcandidateconfig/modules/DepartWindow'
// import ActSelectUserModal from '@views/bms/actcandidateconfig/modules/ActSelectUserModal'

export default {
  name: 'ActVariableConfigModal',
  components: {
    // ActSelectUserModal,
    // DepartWindow,
    // JSelectTableName,
    AInputSearch,
    ACol
  },
  data() {
    return {
      form: this.$form.createForm(this),
      title: '操作',
      width: document.body.clientWidth * 0.6,
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      validatorRules: {
        purpose: { rules: [{ required: 'true', message: '请输入用途！' }] },
        tableName: {},
        fieldName: {},
        fieldDescription: {},
        fieldCondition: {},
        fieldConditionCategory: {},
        tableDescription: {},
        processNodeCode: {}
      },
      url: {
        add: '/actvariableconfig/actVariableConfig/add',
        edit: '/actvariableconfig/actVariableConfig/edit',
        column: '/actcandidateconfig/actCandidateConfig/queryColumnsByTableName',
        fieldName: '/actcandidateconfig/actCandidateConfig/queryColumnsByTableName'
      },
      fieldNameList: [],
      fieldConditionList: [
        {
          text: 'in',
          value: 'in'
        }, {
          text: 'not in',
          value: 'notin'
        },
        {
          text: '<',
          value: '<'
        },
        {
          text: '>',
          value: '>'
        },
        {
          text: '<=',
          value: '<='
        },
        {
          text: '>=',
          value: '>='
        }
      ],
      fieldConditionCategoryList: [
        {
          text: '部门',
          value: 'depart'
        },
        {
          text: '角色',
          value: 'role'
        },
        {
          text: '用户',
          value: 'user'
        },
        {
          text: '自定义方法',
          value: 'function'
        },
        {
          text: '常量',
          value: 'variable'
        }
      ],
      candidateCategoryList: [
        {
          text: '默认',
          value: 'default_value'
        },
        {
          text: '自定义方法',
          value: 'function'
        }
      ],
      tableInfo: {},
      fieldInfo: {},
      fieldConditionCategory: '',
      fieldConditionResultsText: '',
      fieldConditionResults: '',
      roleList: [],
      selectedRole: [],
      currentField: '',//候选类别  字段条件类别中角色 用户公用同一组件，记录是谁打开的组件
      processNodeCodeList: [],
      status: 0,
      statusCheck: false,
      candidateResults: ''
    }
  },
  created() {
  },
  methods: {
    add() {
      this.edit({})
    },
    edit(record) {
      this.initialList()
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'purpose', 'tableName', 'fieldName', 'fieldDescription', 'fieldCondition', 'fieldConditionCategory',
          'tableDescription', 'processNodeCode', 'candidateCategory'))
      })
      if (record.id) {
        this.tableInfo.tableName = record.tableName
        if (this.tableInfo.tableName) {
          this.getFieldNameList()
        }
        this.fieldConditionCategory = record.fieldConditionCategory
        this.fieldConditionResults = record.fieldConditionResults
        this.fieldConditionResultsText = record.fieldConditionResultsText
        if (this.fieldConditionCategory === 'role') {
          this.selectedRole = this.fieldConditionResults.split(',')
        }
        this.status = record.status
        this.statusCheck = record.status == 1 ? true : false
        this.candidateResults = record.candidateResults
      }
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.roleList = []
      this.selectedRole = []
      this.fieldConditionResults = ''
      this.fieldConditionResultsText = ''
      this.tableInfo = {}
      this.fieldInfo = {}
      this.fieldConditionCategory = ''
      this.currentField = ''
      this.status = 0
      this.statusCheck = false
      this.candidateResults = ''
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          let formData = Object.assign(this.model, values)
          formData.fieldConditionResults = this.fieldConditionResults
          formData.fieldConditionResultsText = this.fieldConditionResultsText
          formData.candidateResults = this.candidateResults
          formData.status = this.status
          // console.log('表单提交数据', formData)
          // return
          that.confirmLoading = true
          httpAction(httpurl, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
            that.close()
          })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    openTableNameList() {
      this.$refs.tableName.show()
    },
    tableNameCallback(tableInfo) {
      // console.log(tableInfo)
      this.tableInfo = tableInfo
      this.form.setFieldsValue({ tableName: tableInfo.tableName, tableDescription: tableInfo.tableComment })
      this.form.setFieldsValue({ fieldName: '' })
      this.form.setFieldsValue({ fieldDescription: '' })
      this.fieldInfo = {}
      this.getFieldNameList()
    },
    getFieldNameList() {
      let param = {
        tableName: this.tableInfo.tableName
      }
      getAction(this.url.fieldName, param).then((res) => {
        if (res.success) {
          this.fieldNameList = res.result
        }
      })
    },
    // 字段修改
    fieldNameChange(e) {
      this.fieldInfo = this.fieldNameList.filter(item => item.columnName === e)[0]
      // console.log(this.fieldInfo)
      let fieldDescription = this.fieldInfo.columnComment
      this.form.setFieldsValue({ fieldDescription: fieldDescription })
    },
    //字段条件类别修改
    changeFieldConditionCate(e) {
      this.fieldConditionResults = ''
      this.fieldConditionResultsText = ''
      this.fieldConditionCategory = e
      this.selectedRole = []
    },
    // 搜索用户对应的部门API
    onSearch() {
      this.$refs.departWindow.add()
    },
    // 部门回调
    departCallback(depart) {
      this.fieldConditionResultsText = ''
      this.fieldConditionResults = ''
      if (depart.length > 0) {
        depart.forEach((item, index) => {
          if (index + 1 == depart.length) {
            this.fieldConditionResultsText += item.title
            this.fieldConditionResults += item.value
          } else {
            this.fieldConditionResultsText += item.title + ','
            this.fieldConditionResults += item.value + ','
          }
        })
      }
    },
    initialList() {
      this.initialRoleList()
      // this.initNodeCodeList()
    },
    //角色下拉获取
    initialRoleList() {
      queryall().then((res) => {
        if (res.success) {
          this.roleList = res.result
        } else {
          // console.log(res.message)
        }
      })
    },
    initNodeCodeList() {
      getAction('/actcandidateconfig/actCandidateConfig/queryProcessNode').then((res) => {
        if (res.success) {
          this.processNodeCodeList = res.result
        }
      })
    },
    // 修改角色
    changeRole(e, field) {
      this.currentField = field
      switch (field) {
        case 'fieldCondition':
          if (e.length > 0) {
            this.fieldConditionResultsText = ''
            this.fieldConditionResults = e.join(',')
            //获取角色名逗号拼接给fieldConditionResultsText
            e.forEach(item => {
              this.fieldConditionResultsText += this.roleList.filter(items => items.id === item)[0].roleName + ','
            })
          } else {
            this.fieldConditionResults = ''
            this.fieldConditionResultsText = ''
          }
          break
      }
    },
    openUserModal(field) {
      this.currentField = field
      if (this.currentField == 'fieldCondition') {
        if (this.fieldConditionResults) {
          var record = {
            userIds: this.fieldConditionResults,
            userNames: this.fieldConditionResultsText
          }
          this.$refs.userModal.open(record)
        } else {
          this.$refs.userModal.open({})
        }
      }
    },
    userCallback(users) {
      if (this.currentField == 'fieldCondition') {
        //字段条件结果的用户
        this.fieldConditionResultsText = ''
        this.fieldConditionResults = ''
        if (users.length > 0) {
          users.forEach((item, index) => {
            if (index + 1 == users.length) {
              this.fieldConditionResultsText += item.realname
              this.fieldConditionResults += item.id
            } else {
              this.fieldConditionResultsText += item.realname + ','
              this.fieldConditionResults += item.id + ','
            }
          })
        }
      }
    },
    onChose(checked) {
      if (checked) {
        this.status = 1
        this.statusCheck = true
      } else {
        this.status = 0
        this.statusCheck = false
      }
    },
    //候选类别change
    changeCandidateCategory(e) {
      this.candidateResults = ''
    },
    handleNodeCode(e) {
      if (!e.target.value) {
        this.status = 0
        this.statusCheck = false
      } else {
        this.status = 1
        this.statusCheck = true
      }
    }
  }
}
</script>